<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-03-28
 * Time: 下午 4:26
 */
namespace App;
use Endroid\QrCode\QrCode;
use Model\ActivityMemberTreasureMod;
use Model\ActivityMod;
use Model\ActivitySettingMod;
use Model\ActivityTreasureMod;
use Model\ActivityUiMod;
use Model\ShareMod;
use Model\SponsorCouponMod;
use Model\StorePositionMod;
use Model\WqFansMod;
use Model\WqMemberMod;

class Action
{
	protected $_data = array();
	protected $_result = array('status'=>'error');
	protected $_gpc = array();
	protected $_w = array();
	protected $_uniacid = 0; //公众号id


    private $WqMember = null;  //微擎会员
    private $WqFans = null; //微擎粉丝
    private $StorePosition = null;  //门店职位
    private $ActivitySetting = null;  //活动的配置
    private $ActivityUi = null;   //活动UI
    private $Share = null;  //活动分享配置
    private $ActivityTreasure = null;  //活动投放的宝藏（虚拟宝藏和实体宝藏）
    private $ActivityMemberTreasure = null;  //活动会员抢到的宝藏

	protected function __construct()
	{
		global $_GPC,$_W;
		$this->_gpc = $_GPC;
		$this->_w = $_W;
		$this->_uniacid = $this->_w['account']['uniacid'];
	}

	/**
	 * 接口返回内容处理
	 * @param $_data
	 */
	protected function result($_data)
	{
		if (is_array($_data)) {
			echo json_encode($_data);
		} else {
			echo $_data;
		}
		exit;
	}

    /**
     * 获取，生成一个二维码
     * @param $_dir_name 二维码存放的目录名字
     * @param $_file_name 文件名
     * @param $_url  二维码储存的链接
     * @param $_build 是否重新生成
     * @return mixed
     */
    protected function getQrcode($_dir_name,$_file_name,$_url,$_build = false)
    {
        $_dir = ATTACHMENT_ROOT.'kuyuan_vbz/'.$this->_uniacid.'/'.$_dir_name.'/';
        $_filename = $_dir.$_file_name.'.png';
        $_path = 'kuyuan_vbz/'.$this->_uniacid.'/'.$_dir_name.'/'.$_file_name.'.png';
        if(is_file($_filename) && !$_build){
            return $this->_w['attachurl_local'].$_path;
        }else{
            if(!is_dir($_dir)){
                mkdir($_dir,0777,true);
            }
            $Qrcode = new QrCode($_url);
            $Qrcode->setSize(500);
            $Qrcode->save($_filename);
            return $this->_w['attachurl_local'].$_path;
        }
    }

    /**
     * 通过uid获取用户信息,如果微擎表里没有获取到用户的昵称和头像则手动获取设置微擎表的用户头像和昵称
     * @param $_uid
     * @param array $_return
     * @param number $_count 循环次数
     * @return mixed
     */
    protected function uidToInfo($_uid,Array $_return = array('nickname','avatar'),$_count = 0)
    {
        if(!$this->WqMember instanceof WqMemberMod) $this->WqMember = new WqMemberMod();
        $_member = $this->WqMember->findOne(array('uid'=>$_uid),$_return);
        if($_count ==0){
            if((isset($_member['nickname']) && $_member['nickname'] =='') || (isset($_member['avatar']) && $_member['avatar'] == '')){
                $WxApi = \WeAccount::create();
                $_fans = $this->uidToFans($_uid);
                $_wx_member = $WxApi->fansQueryInfo($_fans['openid']);
                $this->WqMember->update(array('nickname'=>$_wx_member['nickname'],'avatar'=>$_wx_member['headimgurl']),array('uid'=>$_uid));
                return $this->uidToInfo($_uid,$_return,++$_count);
            }
        }
        return $_member;
    }

    /**
     * 通过uid获取用户的粉丝信息
     * @param $_uid
     * @param array $_return
     * @return
     */
    protected function uidToFans($_uid,Array $_return = array('openid'))
    {
        if(!$this->WqFans instanceof WqFansMod) $this->WqFans = new WqFansMod();
        return $this->WqFans->findOne(array('uid'=>$_uid),$_return);
    }


    /**
     * 通过职位id返回职位名字
     * @param $_position_id
     * @return string 返回职位名字
     */
    protected function positionIdToNmae($_position_id)
    {
        if(!$this->StorePosition instanceof StorePositionMod) $this->StorePosition = new StorePositionMod();
        $_position = $this->StorePosition->findOne(array('id'=>$_position_id),array('name'));
        return $_position['name'];
    }

    /**
     * 获取活动的基础配置
     * @param $_activity_id 活动id
     * @param $_return  //返回的字段集合
     * @return array 返回配置集合
     */
    protected function getActivitySetting($_activity_id,Array $_return)
    {
        if(!$this->ActivitySetting instanceof ActivitySettingMod) $this->ActivitySetting = new ActivitySettingMod();
        return $this->ActivitySetting->findOne(array('activity_id'=>$_activity_id),$_return);
    }

    /**
     * 获取活动数据,APP活动端获取一个活动的所有数据，需要缓存
     * @param Activity 活动mod类对象
     * @param activity_id 活动id
     * @return array
     */
    protected function getActivity(ActivityMod $Activity,$_activity_id)
    {
        $_activity = $Activity->findOne(array('uniacid' => $this->_uniacid,'status !='=> 9,'id'=>$_activity_id),array('open3d','init_bz_number','open_distance','bz_number','start','end','bz_win_odds','entity_win_odds','coupon_win_odds','map_coords','shop_model'));
        if($_activity){
            //活动投放区域信息
            $_activity['map_coords'] = json_decode(htmlspecialchars_decode($_activity['map_coords']),true);
            //活动是否投放了虚拟宝藏
            $_activity['put_bz'] = $this->testActivityPutBzEntity($_activity_id,1) ? true : false;
            //活动是否投放了实体奖励
            $_activity['put_entity'] = $this->testActivityPutBzEntity($_activity_id,2) ? true : false;
            //活动是否开启了商场模式，如果开启了商场模式同时也投放了卡券
            $_activity['put_coupon'] = $_activity['shop_model'] == 1 ? true : false;
            //举办方是否投放了卡券
            $_activity['sponsor_coupon'] = $this->testActivityPutCoupon($_activity_id) ? true : false;
            $_activity = array_merge($_activity,$this->getActivityShare($_activity_id));
            //获取活动的地图皮肤设置
            $_ui = $this->getActivityUi($_activity_id);
            if($_ui) $_activity["ui"] = $_ui;
        }
        return $_activity;
    }

    /**
     * 检测指定活动是否投放了卡券
     * @param $_activity_id
     * @return boolean 是否投放了卡券
     */
    private function testActivityPutCoupon($_activity_id)
    {
        $SponsorCoupon = new SponsorCouponMod();
        return $SponsorCoupon->findOne(array('activity_id'=>$_activity_id,'status'=>1),array('id'));
    }

    /*
     * 获取活动分享配置
     * @param activity_id 活动id
     */
    private function getActivityShare($_activity_id)
    {
        $this->Share = new ShareMod();
        $_share = $this->Share->findOne(array('activity_id'=>$_activity_id),array('take_m','open_share'));
        if(!$_share){
            $this->Share->insert(array('activity_id'=>$_activity_id));
            return $this->getActivityShare($_activity_id);
        }
        return $_share;
    }

    /**
     * 获取活动UI设置
     * @param activity_id 活动id
     * @return Array 返回UI数据
     */
    private function getActivityUi($_activity_id)
    {
        $this->ActivityUi = new ActivityUiMod();
        return $this->ActivityUi->findOne(array("activity_id"=>$_activity_id),array("skin"));
    }



    /**
     * 检测活动是否投放了虚拟宝藏和实体奖励
     * @param activity_id 活动id
     * @param type 检测的类型  1=宝藏 2=实体奖励
     * @return boolean 是否开启了指定奖励
     */
    private function testActivityPutBzEntity($_activity_id,$_type)
    {
        if(!$this->ActivityTreasure instanceof ActivityTreasureMod) $this->ActivityTreasure = new ActivityTreasureMod();
        return $this->ActivityTreasure->findOne(array('activity_id'=>$_activity_id,'type'=>$_type),array('id'));
    }


    //----------------卡券状态信息转换-------------------
    /**
     * 通过卡去哪的cost返回卡券的字符串面值和类型
     * @param $_type 卡券的类型
     * @param $_cost json编码后的cost
     * @return array 返回卡券的面值信息
     */
    protected function costToStrcost($_type,$_cost)
    {
        $_cost = json_decode(htmlspecialchars_decode($_cost),true);
        switch($_type){
            case 'dj':
                return array('type'=>'代金券','face_value'=>$_cost['face_value'].'元');
            case 'mj':
                return array('type'=>'满减券','face_value'=>'满'.$_cost['face_value'].'减'.$_cost['minus_value']);
            case 'dh':
                return array('type'=>'兑换券','face_value'=>'兑换'.$_cost['face_value']);
            case 'zk':
                return array('type'=>'折扣券','face_value'=>$_cost['face_value'].'折');
            case 'rc':
                return array('type'=>'入场券','face_value'=>$_cost['face_value'].'入场券');
        }
    }


    /**
     *通过卡券的时间限制类型use_limit_type和时间限制value(limit_time)返回字符串
     * @param  $_type 限制类型
     * @param $_value 值
     * @return 卡券时间限制的字符串
     */
    protected function limitTimeTostring($_type,$_value)
    {
        $_content = '';
        if($_type == '1'){
            $_content = '永久有效';
        }else if($_type == '2'){
            $_content = '有效期至'.date('Y-m-d',$_value);
        }else{
            $_content = '领券后'.$_value.'天内有效';
        }
        return $_content;
    }

    /**
     * 返回指定用户获取宝藏的数量
     * @param $_uid  用户id
     * @param $_activity_id 活动id
     * @param $_treasure_id  宝藏id
     * @param string $_type  类型 bz=数据库=1,2(虚拟宝藏和实体奖励)  coupon=数据库=3(卡券)
     * @return number 抢到的宝藏数量
     */
    protected function userTreasureNumber($_uid,$_activity_id,$_treasure_id,$_type = 'bz')
    {
        if(!$this->ActivityMemberTreasure instanceof ActivityMemberTreasureMod) $this->ActivityMemberTreasure = new ActivityMemberTreasureMod();
        $_where = array('uid'=>$_uid,'activity_id'=>$_activity_id,'treasure_id'=>$_treasure_id);
        if($_type == 'bz'){
            $_where['type <'] = 3;
        }else if($_type == 'coupon'){
            $_where['type'] = 3;
        }
        return $this->ActivityMemberTreasure->sum($_where,'number');
    }

}